Java 26-Day Course - Day 3: Operators and Type Conversion

Day 3: Operators and Type Conversion

Operators are symbols that process data. Java provides various operators including arithmetic, comparison, logical, assignment, and bitwise operators. It is also important to understand type conversion between different data types.

Arithmetic and Assignment Operators

Let’s explore basic math operations and compound assignment operators.

public class ArithmeticOperator {
    public static void main(String[] args) {
        int a = 17;
        int b = 5;

        System.out.println("Addition: " + (a + b));    // 22
        System.out.println("Subtraction: " + (a - b)); // 12
        System.out.println("Multiplication: " + (a * b)); // 85
        System.out.println("Division: " + (a / b));    // 3 (integer division)
        System.out.println("Modulus: " + (a % b));     // 2

        // Compound assignment operators
        int score = 100;
        score += 10;  // score = score + 10 -> 110
        score -= 20;  // score = score - 20 -> 90
        score *= 2;   // score = score * 2  -> 180
        score /= 3;   // score = score / 3  -> 60
        System.out.println("Final score: " + score);

        // Increment/decrement operators
        int count = 5;
        System.out.println(count++); // 5 (postfix: prints then increments)
        System.out.println(count);   // 6
        System.out.println(++count); // 7 (prefix: increments then prints)
    }
}

Comparison and Logical Operators

These operators are used to evaluate conditions.

public class ComparisonLogicalOperator {
    public static void main(String[] args) {
        int x = 10;
        int y = 20;

        // Comparison operators (result: boolean)
        System.out.println(x == y);  // false
        System.out.println(x != y);  // true
        System.out.println(x > y);   // false
        System.out.println(x < y);   // true
        System.out.println(x >= 10); // true
        System.out.println(x <= 5);  // false

        // Logical operators
        boolean isAdult = true;
        boolean hasMoney = false;

        System.out.println(isAdult && hasMoney); // false (AND: both must be true)
        System.out.println(isAdult || hasMoney); // true  (OR: at least one true)
        System.out.println(!isAdult);            // false (NOT: negation)

        // Ternary operator
        int age = 17;
        String status = (age >= 18) ? "adult" : "minor";
        System.out.println(status); // "minor"
    }
}

Implicit Type Conversion (Widening)

Conversion from a smaller type to a larger type happens automatically. No data is lost.

public class AutoCasting {
    public static void main(String[] args) {
        // Implicit conversion: byte -> short -> int -> long -> float -> double
        byte byteVal = 10;
        int intVal = byteVal;      // byte -> int (automatic)
        long longVal = intVal;     // int -> long (automatic)
        double doubleVal = longVal; // long -> double (automatic)

        System.out.println("byte -> int: " + intVal);
        System.out.println("int -> long: " + longVal);
        System.out.println("long -> double: " + doubleVal);

        // Implicit conversion during operations
        int num = 10;
        double result = num / 4.0;  // int is automatically converted to double
        System.out.println("10 / 4.0 = " + result); // 2.5

        // Note: dividing integers produces an integer
        System.out.println("10 / 4 = " + (10 / 4)); // 2 (decimal truncated)
    }
}

Explicit Type Conversion (Narrowing)

When converting from a larger type to a smaller type, you must use a casting operator.

public class ExplicitCasting {
    public static void main(String[] args) {
        // Explicit casting: data loss is possible!
        double pi = 3.14159;
        int intPi = (int) pi;       // Decimal truncated
        System.out.println("double -> int: " + intPi); // 3

        long bigNumber = 300;
        byte smallByte = (byte) bigNumber; // Data loss if out of range
        System.out.println("long -> byte: " + smallByte); // 44 (overflow)

        // String <-> number conversion
        String numStr = "123";
        int parsed = Integer.parseInt(numStr);       // String -> int
        double parsedD = Double.parseDouble("3.14"); // String -> double
        String back = String.valueOf(parsed);        // int -> String
        String back2 = "" + parsed;                  // int -> String (shorthand)

        System.out.println("Parsed: " + parsed);
        System.out.println("String: " + back);

        // char and int conversion
        char ch = 'A';
        int ascii = ch;          // 65
        char fromInt = (char) 66; // 'B'
        System.out.println("ASCII of A: " + ascii);
        System.out.println("Char of 66: " + fromInt);
    }
}

Today’s Exercises

  1. Temperature Converter: Write a program that takes a Celsius temperature (double) and converts it to Fahrenheit. Formula: Fahrenheit = Celsius * 9.0 / 5.0 + 32. Avoid the integer division pitfall.

  2. Even or Odd: Declare an integer variable and use the ternary operator to determine whether it is even or odd. (Use the % operator)

  3. Overflow Experiment: Print what happens when you add 1 to Integer.MAX_VALUE. Cast 200 to a byte type and check the result. Explain in comments why this result occurs.

Was this article helpful?